package servlet;

import javabean.User;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/*
* 登录
*   数据库名称密码，连接数据库，对数据库进行操作
*   post方法：保存和更新资源
 */
@WebServlet("/loginServlet") //设置注解
public class LoginServlet extends HttpServlet {
	protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
		//设置字符编码
		request.setCharacterEncoding("UTF-8");//防止post乱码
		//获取用户名和密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//创建用户对象，设置用户名和密码
		User user=new User();
		user.setUsername(username);
		user.setPassword(password);

		// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
		final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
		final String DB_URL = "jdbc:mysql://localhost:3306/tb_user?serverTimezone=UTC&characterEncoding=utf-8";



		// 数据库的用户名与密码，需要根据自己的设置
		final String USER = "root";
		final String PASS = "123456";
        /*
        *创建conn实现数据库连接
        * 创建stmt用来传输sql语句
        * 创建rs来接受stmt.executeQuery,返回所有符合条件的对象的集合
         */
		Connection conn = null;
		Statement stmt = null;
		try{
			// 注册 JDBC 驱动
			Class.forName(JDBC_DRIVER);
			// 打开链接
			conn = DriverManager.getConnection(DB_URL,USER,PASS);
			// 执行查询
			stmt = conn.createStatement();
			String sql;
			sql = " SELECT * FROM user where username = '"+user.getUsername()+"' and password = '"+user.getPassword()+"'";
			//System.out.println(user.getUsername()+user.getPassword());
			ResultSet rs = stmt.executeQuery(sql);
            //rs.next()不为空，为true,
			if(rs.next()){
				String username1 = rs.getString("username");
				String password1  = rs.getString("password");
				System.out.println("该用户存在");
				if(user.getUsername().equals(username1) && user.getPassword().equals(password1)){
					//创建User对象保存账号、密码
				    User usertemp = new User();
					usertemp.setUsername(username1);
					usertemp.setPassword(password1);
                    //用session记录登录成功
                    request.getSession().setAttribute("usertemp", usertemp);
                    //跳转到首页
                    //response.sendRedirect("main.jsp");
                    //request.setAttribute("usertemp", usertemp);
					request.getRequestDispatcher("/main.jsp").forward(request, response);
				}
			}
			else  {
				System.out.println("该用户不存在");
				//response.getWriter().println("alert('用户名或密码错误，请重新输入！')");
				request.setAttribute("errorMessage", "用户名或密码不正确！");
				request.getRequestDispatcher("login.jsp").forward(request, response);
				//response.sendRedirect(request.getContextPath()+"/Login.jsp");
			}
			// 完成后关闭
			rs.close();
			stmt.close();
			conn.close();
		}catch(Exception se){
			// 处理 JDBC 错误
			se.printStackTrace();
		} finally {
			// 关闭资源
			try {
				if (stmt != null) stmt.close();
				if (conn != null) conn.close();
			}
			catch (Exception se) {
				se.printStackTrace();
			}
		}
	}


}